import { reqCoupon } from '../../request/api'

//初始状态
const initState = {
    coupon: [],
    n: 0,
    arr: ['未使用', '已使用', '已失效']
}

// actionType
const TYPES = {
    COUPON_CHANGE_COUPON: 'COUPON_CHANGE_COUPON',
    COUPON_CHANGE_N: 'COUPON_CHANGE_N'
}

// reducer
const reducer = (state = initState, action) => {
    switch (action.type) {
        case TYPES.COUPON_CHANGE_COUPON:
            return {
                ...state,
                coupon: action.coupon
            }
        case TYPES.COUPON_CHANGE_N:
            return {
                ...state,
                n: action.n
            }
        default:
            return state;
    }
}

// actionCreators
export const actions = {
    changeCoupon: (coupon) => ({ type: TYPES.COUPON_CHANGE_COUPON, coupon }),
    // 请求优惠券
    requestCoupon: () => (dispatch, getState) => {
        let coupon = getCoupon(getState())
        if (coupon.length > 0) {
            return;
        }
        reqCoupon().then(res => {
            if (res.data.code == 200) {
                dispatch(actions.changeCoupon(res.data.list))
            }
        })
    },
    changeN: (n) => ({ type: TYPES.COUPON_CHANGE_N, n })
}
// selectors
export const getCoupon = state => state.coupon.coupon;
export const getN = state => state.coupon.n;
export const getArr = state => state.coupon.arr;
export const showCoupon=state=>{
    let coupon=getCoupon(state);
    let n=getN(state);
    return coupon.length>0?coupon[n].content:[]
}

export default reducer